package cn.dodgeball.java;

import cn.dodgeball.util.Const;
import cn.dodgeball.util.PClass;

import javax.swing.*;
import java.awt.*;

public class Square extends JPanel implements Runnable {
    private final int width = Const.WIDTH;
    private final int height = Const.HEIGHT;
    private final int radius = Const.squareRadius;
    JLabel shield;
    ImageIcon imageIcon = new ImageIcon("src/cn/dodgeball/resources/img/shield.png");

    private boolean isAlive = true;

    public Square() {
        setLayout(null);
        setBackground(Const.squareColor);
        setBounds((int) (Const.FRAME_WIDTH * 0.5), (int) (Const.FRAME_HEIGHT * 0.5), Const.squareRadius * 2, Const.squareRadius * 2);

        Image image = imageIcon.getImage().getScaledInstance(radius * 2, radius * 2, Image.SCALE_SMOOTH);
        imageIcon.setImage(image);
        shield = new JLabel(imageIcon);
        shield.setBounds(0, 0, radius * 2, radius * 2);

        shield.setVisible(false);
        add(shield);
    }

    private boolean isCrash(int x, int y, int r) {
        return x - r < 0 || x + r > width || y - r < 0 || y + r > height;
    }

    @Override
    public void run() {
        while (isAlive) {
            setVisible(true);
            if (Const.isGaming && !Const.isGold && isCrash(PClass.mousePosition.x, PClass.mousePosition.y, Const.squareRadius)) {
                Const.isGaming = false;
                PClass.gamePanel.gameOver();
                System.out.print("撞墙出局" + "(" + PClass.mousePosition.x + "." + PClass.mousePosition.y + ")" + "\n");
            }

            setBounds(PClass.mousePosition.x - Const.squareRadius, PClass.mousePosition.y - Const.squareRadius, getWidth(), getHeight());
            repaint();

            shield.setVisible(Const.isGold);

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void removeNotify() {
        super.removeNotify();
        isAlive = false;
    }
}
